# -*- coding:utf-8 -*-  
from google.appengine.ext import webapp
import os 
from google.appengine.ext.webapp import template
from datetime import timedelta
import time
import random
from session import session
import md5

class mywork():
    def render(self, name, data):
        self.temp = os.path.join(os.path.dirname(__file__), 'template', name)
        return template.render(self.temp, data)
    def dosession(self, key):
        requestkey = ''.join([key, str(time.time()), str(random.randint(0, 100000))])
        newkey = md5.md5(requestkey).hexdigest()
        return newkey
    def doheader(self, sessionkey, expiresday):
        '''expires=some day'''
        expires_date = datetime.datetime.utcnow() + datetime.timedelta(expiresday)
        expires_str = expires_date.strftime("%d %b %Y %H:%M:%S GMT")
        cookie = ''.join(['session', '=', sessionkey, ])
        header = {'Expires':expires_str,
                'Set-Cookie':cookie}
        return header
    def checkuser(self, username):
        user = user.all().filter('username =', args['username'])
        if user:
            return True
        else:
            return False
    def databasework(self, args):
        user = user.all()
        user.username = args['username']
        user.password = args['password']
        user.password = args['gender']
        user.collage = args['collage']
        user.school = args['school']
        user.major = args['major']
        user.put()
    
        
        
        
        
        

@session(expire=timedelta(minutes=60))
class userlogin(webapp.RequestHandler, mywork):
    def get(self):
        out_html = mywork.render('login.html', data={})
        self.response.out.write(out_html)
    def post(self):
        past_data = {'username':self.request.get('username'),
                   'password':self.request.get('password'),
                   'gender':self.request.get('gender'),
                   'collage':self.request.get('collage'),
                   'school':self.request.get('school'),
                   'major':self.request.get('major')}
        self.session['user_name'] = post_data['username']
        self.session['session'] = mywork.dosession(past_data['username'])
        myheader = mywork.doheader(self, self.session['session'], 365)
        for i in myheader.iteritems():
             self.response.headers.add_header(i[0], i[1])
        out_html = mywork.render('login.html', data={})
        
        
